# -*- coding: utf-8 -*-

# @version        : 1.0
# @Create Time    : 2021/10/18 22:19
# @File           : db_base.py
# @IDE            : PyCharm
# @desc           : 数据库公共 ORM 模型
from sqlalchemy import Boolean, Column, DateTime, Integer, func
from sqlalchemy.inspection import inspect

from db.db import Base


# 使用命令：alembic init alembic 初始化迁移数据库环境
# 这时会生成alembic文件夹 和 alembic.ini文件
class BaseModel(Base):
    """
    公共 ORM 模型，基表
    """

    __abstract__ = True

    id = Column(Integer, primary_key=True, comment="主键ID")
    create_datetime = Column(DateTime, server_default=func.now(), comment="创建时间")
    update_datetime = Column(
        DateTime, server_default=func.now(), onupdate=func.now(), comment="更新时间"
    )
    delete_datetime = Column(DateTime, nullable=True, comment="删除时间")
    is_delete = Column(Boolean, default=False, comment="是否软删除")
    # created_at = Column(DateTime, default=datetime.now())

    @classmethod
    def get_column_attrs(cls) -> list:
        """
        获取模型中除 relationships 外的所有字段名称
        :return:
        """
        mapper = inspect(cls)
        return mapper.columns.keys()

    @classmethod
    def get_attrs(cls) -> list:
        """
        获取模型所有字段名称
        :return:
        """
        mapper = inspect(cls)
        return mapper.attrs.keys()

    @classmethod
    def get_relationships_attrs(cls) -> list:
        """
        获取模型中 relationships 所有字段名称
        :return:
        """
        mapper = inspect(cls)
        return mapper.relationships.keys()

    def to_dict(self) -> dict:
        """将模型对象转换为字典形式"""
        return {
            column.name: getattr(self, column.name) for column in self.__table__.columns
        }
